// 后台服务脚本
var API_BASE = 'http://127.0.0.1:6006/api/v1';

// 日志函数
function log(level, message, data) {
  var timestamp = new Date().toISOString();
  console.log('[' + timestamp + '] [' + level + '] ' + message);
  if (data) {
    console.log('Details:', data);
  }
}

// 监听安装事件
chrome.runtime.onInstalled.addListener(function() {
  log('INFO', 'Video2Text插件已安装');
});

// 处理API请求
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.type === 'SEND_TO_BACKEND') {
    var audioData = request.audioData;
    
    // 打印请求信息
    log('INFO', '发送音频数据到后端', {
      endpoint: API_BASE + '/audio/process',
      audioData: {
        type: audioData.type,
        size: audioData.size,
        arraySize: audioData.array.length,
        filename: audioData.filename
      }
    });
    
    // 验证数据完整性
    if (audioData.size !== audioData.array.length) {
      log('ERROR', '音频数据不完整', {
        expectedSize: audioData.size,
        actualSize: audioData.array.length
      });
      sendResponse({
        success: false,
        error: '音频数据不完整'
      });
      return true;
    }
    
    // 将数组转回ArrayBuffer
    var arrayBuffer = new Uint8Array(audioData.array).buffer;
    
    // 创建Blob
    var blob = new Blob([arrayBuffer], { type: audioData.type });
    log('INFO', '创建Blob对象', {
      size: blob.size,
      type: blob.type
    });
    
    // 创建FormData
    var formData = new FormData();
    formData.append('audio', blob, audioData.filename);
    
    // 发送请求
    fetch(API_BASE + '/audio/process', {
      method: 'POST',
      body: formData,
      headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      mode: 'cors'
    })
    .then(function(response) {
      log('INFO', '收到响应', {
        status: response.status,
        statusText: response.statusText,
        headers: Object.fromEntries(response.headers.entries())
      });
      
      if (!response.ok) {
        return response.text().then(function(text) {
          throw new Error('API请求失败: ' + response.status + ' - ' + text);
        });
      }
      return response.json();
    })
    .then(function(data) {
      log('INFO', '请求成功', data);
      sendResponse({ success: true, data: data });
    })
    .catch(function(error) {
      log('ERROR', '请求失败', error);
      sendResponse({ success: false, error: error.message });
    });
    
    return true; // 保持消息通道开启
  }
  else if (request.type === 'TEXT_OPTIMIZE') {
    var raw_text = request.data.text;
    
    // 打印请求信息
    log('INFO', '发送原始文本到后端', {
      endpoint: API_BASE + '/text/optimize',
      data: {text: raw_text}
    });
    
    // 发送请求
    fetch(API_BASE + '/text/optimize', {
      method: 'POST',
      body: JSON.stringify({
        text: raw_text,
      }),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      mode: 'cors'
    })
    .then(function(response) {
      log('INFO', '收到text optimize api fetch响应', {
        status: response.status,
        statusText: response.statusText
      });
      
      if (!response.ok) {
        return response.text().then(function(text) {
          throw new Error('API请求失败: ' + response.status + ' - ' + text);
        });
      }
      return response.json();
    })
    .then(function(data) {
      log('INFO', 'background中text optimize请求成功', data);
      sendResponse({ 
        success: true, 
        data: data.data});
    })
    .catch(function(error) {
      log('ERROR', '请求失败', error);
      sendResponse({ success: false, error: error.message });
    });
    
    return true; // 保持消息通道开启
  }
}); 